package com.qf.kdxf.controller;

import com.qf.kdxf.service.impl.TextIdentifyServiceImpl;
import com.qf.kdxf.util.common.FileUtil;
import com.qf.kdxf.util.common.HttpUtil;
import com.qf.kdxf.util.common.UploadFile;
import com.qf.kdxf.util.common.XunfeiOCRParser;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/textidentify")
public class TextIdentifyController {

    @Autowired
    TextIdentifyServiceImpl textIdentifyService;

    /**
     * 手写文字识别
     */
    @RequestMapping("/textidentify")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file,
                                      HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();

        try {
            // 保存文件
            String path = request.getServletContext().getRealPath("/");
            String filePath = UploadFile.upload(file, path);

            // 准备API请求
            Map<String, String> header = textIdentifyService.constructHeader("en", "false");
            byte[] imageByteArray = FileUtil.read2ByteArray(filePath);
            String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
            String bodyParam = "image=" + imageBase64;

            // 调用讯飞API
            String apiResult = HttpUtil.doPost(
                    "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting",
                    header,
                    bodyParam
            );

            // 使用工具类解析结果
            String parsedResult = XunfeiOCRParser.parseOCRResult(apiResult);

            resultMap.put("success", true);
            resultMap.put("result", parsedResult);

        } catch (Exception e) {
            resultMap.put("success", false);
            resultMap.put("result", "处理请求时出错: " + e.getMessage());
        }

        return resultMap;
    }
}